package org.example.trigger.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.example.types.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author yinghuashen
 * @version 1.0
 * @description
 * @date 2025/3/8 14:55
 */

@Slf4j
public class DCCInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("DCCInterceptor拦截器拦截请求");
        // 获取请求头中的token
        String jwtToken = request.getHeader("Authorization");
        // 判断token是否为空
        if (jwtToken == null || jwtToken.isEmpty()) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 验证token是否有效
        Map<String, Object> claim = JwtUtils.checkToken(jwtToken);
        if (claim == null) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 从Claim中获取手机号
        Object role = claim.get("role");
        if (!"admin".equals(role)) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }
}
